home *** CD-ROM | disk | FTP | other *** search
/ Aminet 21 / Aminet 21 (1997)(GTI - Schatztruhe)[!][Oct 1997].iso / Aminet / dev / c / BinaryTrees.lzh / ubi_SplayTree.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-07-26  |  19.2 KB  |  464 lines

  1. /* ========================================================================== **
  2.  *                              ubi_SplayTree.c
  3.  *
  4.  *  Copyright (C) 1993-1995 by Christopher R. Hertel
  5.  *
  6.  *  Email: crh@ubiqx.mn.org
  7.  * -------------------------------------------------------------------------- **
  8.  *
  9.  *  This module implements "splay" trees.  Splay trees are binary trees
  10.  *  that are rearranged (splayed) whenever a node is accessed.  The
  11.  *  splaying process *tends* to make the tree bushier (improves balance),
  12.  *  and the nodes that are accessed most frequently *tend* to be closer to
  13.  *  the top.
  14.  *
  15.  *  References: "Self-Adjusting Binary Search Trees", by Daniel Sleator and
  16.  *              Robert Tarjan.  Journal of the Association for Computing
  17.  *              Machinery Vol 32, No. 3, July 1985 pp. 652-686
  18.  *
  19.  * -------------------------------------------------------------------------- **
  20.  *
  21.  *  This library is free software; you can redistribute it and/or
  22.  *  modify it under the terms of the GNU Library General Public
  23.  *  License as published by the Free Software Foundation; either
  24.  *  version 2 of the License, or (at your option) any later version.
  25.  *
  26.  *  This library is distributed in the hope that it will be useful,
  27.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  28.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  29.  *  Library General Public License for more details.
  30.  *
  31.  *  You should have received a copy of the GNU Library General Public
  32.  *  License along with this library; if not, write to the Free
  33.  *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  34.  *
  35.  * -------------------------------------------------------------------------- **
  36.  *
  37.  * $Log: ubi_SplayTree.c,v $
  38.  * Revision 2.5  1997/07/26 04:15:42  crh
  39.  * + Cleaned up a few minor syntax annoyances that gcc discovered for me.
  40.  * + Changed ubi_TRUE and ubi_FALSE to ubi_trTRUE and ubi_trFALSE.
  41.  *
  42.  * Revision 2.4  1997/06/03 04:42:21  crh
  43.  * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid causing
  44.  * problems.
  45.  *
  46.  * Revision 2.3  1995/10/03 22:19:07  CRH
  47.  * Ubisized!
  48.  * Also, added the function ubi_sptSplay().
  49.  *
  50.  * Revision 2.1  95/03/09  23:54:42  CRH
  51.  * Added the ModuleID static string and function.  These modules are now
  52.  * self-identifying.
  53.  * 
  54.  * Revision 2.0  95/02/27  22:34:46  CRH
  55.  * This module was updated to match the interface changes made to the
  56.  * ubi_BinTree module.  In particular, the interface to the Locate() function
  57.  * has changed.  See ubi_BinTree for more information on changes and new
  58.  * functions.
  59.  *
  60.  * The revision number was also upped to match ubi_BinTree.
  61.  *
  62.  * Revision 1.1  93/10/18  20:35:16  CRH
  63.  * I removed the hard-coded logical device names from the include file
  64.  * specifications.  CRH
  65.  *
  66.  * Revision 1.0  93/10/15  23:00:15  CRH
  67.  * With this revision, I have added a set of #define's that provide a single,
  68.  * standard API to all existing tree modules.  Until now, each of the three
  69.  * existing modules had a different function and typedef prefix, as follows:
  70.  *
  71.  *       Module        Prefix
  72.  *     ubi_BinTree     ubi_bt
  73.  *     ubi_AVLtree     ubi_avl
  74.  *     ubi_SplayTree   ubi_spt
  75.  *
  76.  * To further complicate matters, only those portions of the base module
  77.  * (ubi_BinTree) that were superceeded in the new module had the new names.
  78.  * For example, if you were using ubi_AVLtree, the AVL node structure was
  79.  * named "ubi_avlNode", but the root structure was still "ubi_btRoot".  Using
  80.  * SplayTree, the locate function was called "ubi_sptLocate", but the next
  81.  * and previous functions remained "ubi_btNext" and "ubi_btPrev".
  82.  *
  83.  * This was not too terrible if you were familiar with the modules and knew
  84.  * exactly which tree model you wanted to use.  If you wanted to be able to
  85.  * change modules (for speed comparisons, etc), things could get messy very
  86.  * quickly.
  87.  *
  88.  * So, I have added a set of defined names that get redefined in any of the
  89.  * descendant modules.  To use this standardized interface in your code,
  90.  * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
  91.  * "ubi_tr".  The "ubi_tr" names will resolve to the correct function or
  92.  * datatype names for the module that you are using.  Just remember to
  93.  * include the header for that module in your program file.  Because these
  94.  * names are handled by the preprocessor, there is no added run-time
  95.  * overhead.
  96.  *
  97.  * Note that the original names do still exist, and can be used if you wish
  98.  * to write code directly to a specific module.  This should probably only be
  99.  * done if you are planning to implement a new descendant type, such as
  100.  * red/black trees.  CRH
  101.  *
  102.  * Revision 0.1  93/04/25  22:03:32  CRH
  103.  * Simply changed the <exec/types.h> #include reference the .c file to
  104.  * use <stdlib.h> instead.  The latter is portable, the former is not.
  105.  *
  106.  * Revision 0.0  93/04/21  23:05:52  CRH
  107.  * Initial version, written by Christopher R. Hertel.
  108.  * This module implements Splay Trees using the ubi_BinTree module as a basis.
  109.  *
  110.  * ========================================================================== **
  111.  */
  112.  
  113. #include <stdlib.h>        /* Defines NULL for us.                */
  114. #include "ubi_SplayTree.h" /* Header for THIS module.             */
  115.  
  116. /* ========================================================================== **
  117.  * Static data.
  118.  */
  119.  
  120. static char ModuleID[] = "ubi_SplayTree\n\
  121. \t$Revision: 2.5 $\n\
  122. \t$Date: 1997/07/26 04:15:42 $\n\
  123. \t$Author: crh $\n";
  124.  
  125.  
  126. /* ========================================================================== **
  127.  * Private functions...
  128.  */
  129.  
  130. static void Rotate( ubi_btNodePtr p )
  131.   /* ------------------------------------------------------------------------ **
  132.    * This function performs a single rotation, moving node *p up one level
  133.    * in the tree.
  134.    *
  135.    *  Input:    p - a pointer to an ubi_btNode in a tree.
  136.    *
  137.    *  Output:   None.
  138.    *
  139.    *  Notes:    This implements a single rotation in either direction (left
  140.    *            or right).  This is the basic building block of all splay
  141.    *            tree rotations.
  142.    * ------------------------------------------------------------------------ **
  143.    */
  144.   {
  145.   ubi_btNodePtr parentp;
  146.   ubi_btNodePtr tmp;
  147.   char          way;
  148.   char          revway;
  149.  
  150.   parentp = p->Link[PARENT];    /* Find parent. */
  151.  
  152.   if( parentp )                 /* If no parent, then we're already the root. */
  153.     {
  154.     way     = p->gender;
  155.     revway  = RevWay(way);
  156.     tmp     = p->Link[revway];
  157.  
  158.     parentp->Link[way]  = tmp;
  159.     if( tmp )
  160.       {
  161.       tmp->Link[PARENT] = parentp;
  162.       tmp->gender       = way;
  163.       }
  164.  
  165.     tmp                 = parentp->Link[PARENT];
  166.     p->Link[PARENT]     = tmp;
  167.     p->gender           = parentp->gender;
  168.     if( tmp )
  169.       tmp->Link[p->gender] = p;
  170.  
  171.     parentp->Link[PARENT] = p;
  172.     parentp->gender       = revway;
  173.     p->Link[revway]       = parentp;
  174.     }
  175.   } /* Rotate */
  176.  
  177. static ubi_btNodePtr Splay( ubi_btNodePtr SplayWithMe )
  178.   /* ------------------------------------------------------------------------ **
  179.    * Move the node indicated by SplayWithMe to the root of the tree by
  180.    * splaying the tree.
  181.    *
  182.    *  Input:  SplayWithMe - A pointer to an ubi_btNode within a tree.
  183.    *
  184.    *  Output: A pointer to the root of the splay tree (i.e., the same as
  185.    *          SplayWithMe).
  186.    * ------------------------------------------------------------------------ **
  187.    */
  188.   {
  189.   ubi_btNodePtr parent;
  190.  
  191.   while( (parent = SplayWithMe->Link[PARENT]) )
  192.     {
  193.     if( parent->gender == SplayWithMe->gender )       /* Zig-Zig */
  194.       Rotate( parent );
  195.     else
  196.       {
  197.       if( EQUAL != parent->gender )                   /* Zig-Zag */
  198.         Rotate( SplayWithMe );
  199.       }
  200.     Rotate( SplayWithMe );                            /* Zig */
  201.     } /* while */
  202.   return( SplayWithMe );
  203.   } /* Splay */
  204.  
  205. /* ========================================================================== **
  206.  * Exported utilities.
  207.  */
  208.  
  209. ubi_trBool ubi_sptInsert( ubi_btRootPtr  RootPtr,
  210.                           ubi_btNodePtr  NewNode,
  211.                           ubi_btItemPtr  ItemPtr,
  212.                           ubi_btNodePtr *OldNode )
  213.   /* ------------------------------------------------------------------------ **
  214.    * This function uses a non-recursive algorithm to add a new element to the
  215.    * splay tree.
  216.    *
  217.    *  Input:   RootPtr  -  a pointer to the ubi_btRoot structure that indicates
  218.    *                       the root of the tree to which NewNode is to be added.
  219.    *           NewNode  -  a pointer to an ubi_btNode structure that is NOT
  220.    *                       part of any tree.
  221.    *           ItemPtr  -  A pointer to the sort key that is stored within
  222.    *                       *NewNode.  ItemPtr MUST point to information stored
  223.    *                       in *NewNode or an EXACT DUPLICATE.  The key data
  224.    *                       indicated by ItemPtr is used to place the new node
  225.    *                       into the tree.
  226.    *           OldNode  -  a pointer to an ubi_btNodePtr.  When searching
  227.    *                       the tree, a duplicate node may be found.  If
  228.    *                       duplicates are allowed, then the new node will
  229.    *                       be simply placed into the tree.  If duplicates
  230.    *                       are not allowed, however, then one of two things
  231.    *                       may happen.
  232.    *                       1) if overwritting *is not* allowed, this
  233.    *                          function will return FALSE (indicating that
  234.    *                          the new node could not be inserted), and
  235.    *                          *OldNode will point to the duplicate that is
  236.    *                          still in the tree.
  237.    *                       2) if overwritting *is* allowed, then this
  238.    *                          function will swap **OldNode for *NewNode.
  239.    *                          In this case, *OldNode will point to the node
  240.    *                          that was removed (thus allowing you to free
  241.    *                          the node).
  242.    *                          **  If you are using overwrite mode, ALWAYS  **
  243.    *                          ** check the return value of this parameter! **
  244.    *                 Note: You may pass NULL in this parameter, the
  245.    *                       function knows how to cope.  If you do this,
  246.    *                       however, there will be no way to return a
  247.    *                       pointer to an old (ie. replaced) node (which is
  248.    *                       a problem if you are using overwrite mode).
  249.    *
  250.    *  Output:  a boolean value indicating success or failure.  The function
  251.    *           will return FALSE if the node could not be added to the tree.
  252.    *           Such failure will only occur if duplicates are not allowed,
  253.    *           nodes cannot be overwritten, AND a duplicate key was found
  254.    *           within the tree.
  255.    * ------------------------------------------------------------------------ **
  256.    */
  257.   {
  258.   ubi_btNodePtr OtherP;
  259.  
  260.   if( !(OldNode) )
  261.     OldNode = &OtherP;
  262.  
  263.   if( ubi_btInsert( RootPtr, NewNode, ItemPtr, OldNode ) )
  264.     {
  265.     RootPtr->root = Splay( NewNode );
  266.     return( ubi_trTRUE );
  267.     }
  268.  
  269.   /* Splay the unreplacable, duplicate keyed, unique, old node. */
  270.   RootPtr->root = Splay( (*OldNode) );
  271.   return( ubi_trFALSE );
  272.   } /* ubi_sptInsert */
  273.  
  274. ubi_btNodePtr ubi_sptRemove( ubi_btRootPtr RootPtr, ubi_btNodePtr DeadNode )
  275.   /* ------------------------------------------------------------------------ **
  276.    * This function removes the indicated node from the tree.
  277.    *
  278.    *  Input:   RootPtr  -  A pointer to the header of the tree that contains
  279.    *                       the node to be removed.
  280.    *           DeadNode -  A pointer to the node that will be removed.
  281.    *
  282.    *  Output:  This function returns a pointer to the node that was removed
  283.    *           from the tree (ie. the same as DeadNode).
  284.    *
  285.    *  Note:    The node MUST be in the tree indicated by RootPtr.  If not,
  286.    *           strange and evil things will happen to your trees.
  287.    * ------------------------------------------------------------------------ **
  288.    */
  289.   {
  290.   ubi_btNodePtr p;
  291.  
  292.   (void)Splay( DeadNode );                  /* Move dead node to root.        */
  293.   if( (p = DeadNode->Link[LEFT]) )          /* If left subtree exists...      */
  294.     {
  295.     ubi_btNodePtr q = DeadNode->Link[RIGHT];
  296.  
  297.     p->Link[PARENT] = NULL;                 /* Left subtree node becomes root.*/
  298.     p->gender       = PARENT;
  299.     p               = ubi_btLast( p );      /* Find rightmost left tree node..*/
  300.     p->Link[RIGHT]  = q;                    /* ...attach right tree.          */
  301.     if( q )
  302.       q->Link[PARENT] = p;
  303.     RootPtr->root   = Splay( p );           /* Resplay at p.                  */
  304.     }
  305.   else
  306.     {
  307.     if( (p = DeadNode->Link[RIGHT]) )       /* No left, but right subtree...  */
  308.       {                                     /* ...exists...                   */
  309.       p->Link[PARENT] = NULL;               /* Right subtree root becomes...  */
  310.       p->gender       = PARENT;             /* ...overall tree root.          */
  311.       RootPtr->root   = p;
  312.       }
  313.     else
  314.       RootPtr->root = NULL;                 /* No subtrees => empty tree.     */
  315.     }
  316.  
  317.   (RootPtr->count)--;                       /* Decrement node count.          */
  318.   return( DeadNode );                       /* Return pointer to pruned node. */
  319.   } /* ubi_sptRemove */
  320.  
  321. ubi_btNodePtr ubi_sptLocate( ubi_btRootPtr RootPtr,
  322.                              ubi_btItemPtr FindMe,
  323.                              ubi_trCompOps CompOp )
  324.   /* ------------------------------------------------------------------------ **
  325.    * The purpose of ubi_btLocate() is to find a node or set of nodes given
  326.    * a target value and a "comparison operator".  The Locate() function is
  327.    * more flexible and (in the case of trees that may contain dupicate keys)
  328.    * more precise than the ubi_btFind() function.  The latter is faster,
  329.    * but it only searches for exact matches and, if the tree contains
  330.    * duplicates, Find() may return a pointer to any one of the duplicate-
  331.    * keyed records.
  332.    *
  333.    *  Input:
  334.    *     RootPtr  -  A pointer to the header of the tree to be searched.
  335.    *     FindMe   -  An ubi_btItemPtr that indicates the key for which to
  336.    *                 search.
  337.    *     CompOp   -  One of the following:
  338.    *                    CompOp     Return a pointer to the node with
  339.    *                    ------     ---------------------------------
  340.    *                   ubi_trLT - the last key value that is less
  341.    *                              than FindMe.
  342.    *                   ubi_trLE - the first key matching FindMe, or
  343.    *                              the last key that is less than
  344.    *                              FindMe.
  345.    *                   ubi_trEQ - the first key matching FindMe.
  346.    *                   ubi_trGE - the first key matching FindMe, or the
  347.    *                              first key greater than FindMe.
  348.    *                   ubi_trGT - the first key greater than FindMe.
  349.    *  Output:
  350.    *     A pointer to the node matching the criteria listed above under
  351.    *     CompOp, or NULL if no node matched the criteria.
  352.    *
  353.    *  Notes:
  354.    *     In the case of trees with duplicate keys, Locate() will behave as
  355.    *     follows:
  356.    *
  357.    *     Find:  3                       Find: 3
  358.    *     Keys:  1 2 2 2 3 3 3 3 3 4 4   Keys: 1 1 2 2 2 4 4 5 5 5 6
  359.    *                  ^ ^         ^                   ^ ^
  360.    *                 LT EQ        GT                 LE GE
  361.    *
  362.    *     That is, when returning a pointer to a node with a key that is LESS
  363.    *     THAN the target key (FindMe), Locate() will return a pointer to the
  364.    *     LAST matching node.
  365.    *     When returning a pointer to a node with a key that is GREATER
  366.    *     THAN the target key (FindMe), Locate() will return a pointer to the
  367.    *     FIRST matching node.
  368.    *
  369.    *  See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
  370.    * ------------------------------------------------------------------------ **
  371.    */
  372.   {
  373.   ubi_btNodePtr p;
  374.  
  375.   p = ubi_btLocate( RootPtr, FindMe, CompOp );
  376.   if( p )
  377.     RootPtr->root = Splay( p );
  378.   return( p );
  379.   } /* ubi_sptLocate */
  380.  
  381. ubi_btNodePtr ubi_sptFind( ubi_btRootPtr RootPtr,
  382.                            ubi_btItemPtr FindMe )
  383.   /* ------------------------------------------------------------------------ **
  384.    * This function performs a non-recursive search of a tree for any node
  385.    * matching a specific key.
  386.    *
  387.    *  Input:
  388.    *     RootPtr  -  a pointer to the header of the tree to be searched.
  389.    *     FindMe   -  a pointer to the key value for which to search.
  390.    *
  391.    *  Output:
  392.    *     A pointer to a node with a key that matches the key indicated by
  393.    *     FindMe, or NULL if no such node was found.
  394.    *
  395.    *  Note:   In a tree that allows duplicates, the pointer returned *might
  396.    *          not* point to the (sequentially) first occurance of the
  397.    *          desired key.  In such a tree, it may be more useful to use
  398.    *          ubi_sptLocate().
  399.    * ------------------------------------------------------------------------ **
  400.    */
  401.   {
  402.   ubi_btNodePtr p;
  403.  
  404.   p = ubi_btFind( RootPtr, FindMe );
  405.   if( p )
  406.     RootPtr->root = Splay( p );
  407.   return( p );
  408.   } /* ubi_sptFind */
  409.  
  410. void ubi_sptSplay( ubi_btRootPtr RootPtr,
  411.                    ubi_btNodePtr SplayMe )
  412.   /* ------------------------------------------------------------------------ **
  413.    *  This function allows you to splay the tree at a given node, thus moving
  414.    *  the node to the top of the tree.
  415.    *
  416.    *  Input:
  417.    *     RootPtr  -  a pointer to the header of the tree to be splayed.
  418.    *     SplayMe  -  a pointer to a node within the tree.  This will become
  419.    *                 the new root node.
  420.    *  Output: None.
  421.    *
  422.    *  Notes:  This is an uncharacteristic function for this group of modules
  423.    *          in that it provides access to the internal balancing routines,
  424.    *          which would normally be hidden.
  425.    *          Splaying the tree will not damage it (assuming that I've done
  426.    *          *my* job), but there is overhead involved.  I don't recommend
  427.    *          that you use this function unless you understand the underlying
  428.    *          Splay Tree principles involved.
  429.    * ------------------------------------------------------------------------ **
  430.    */
  431.   {
  432.   RootPtr->root = Splay( SplayMe );
  433.   } /* ubi_sptSplay */
  434.  
  435. int ubi_sptModuleID( int size, char *list[] )
  436.   /* ------------------------------------------------------------------------ **
  437.    * Returns a set of strings that identify the module.
  438.    *
  439.    *  Input:  size  - The number of elements in the array <list>.
  440.    *          list  - An array of pointers of type (char *).  This array
  441.    *                  should, initially, be empty.  This function will fill
  442.    *                  in the array with pointers to strings.
  443.    *  Output: The number of elements of <list> that were used.  If this value
  444.    *          is less than <size>, the values of the remaining elements are
  445.    *          not guaranteed.
  446.    *
  447.    *  Notes:  Please keep in mind that the pointers returned indicate strings
  448.    *          stored in static memory.  Don't free() them, don't write over
  449.    *          them, etc.  Just read them.
  450.    * ------------------------------------------------------------------------ **
  451.    */
  452.   {
  453.   if( size > 0 )
  454.     {
  455.     list[0] = ModuleID;
  456.     if( size > 1 )
  457.       return( 1 + ubi_btModuleID( --size, &(list[1]) ) );
  458.     return( 1 );
  459.     }
  460.   return( 0 );
  461.   } /* ubi_sptModuleID */
  462.  
  463. /* ================================ The End ================================= */
  464.